package com.xxc.smartcar.utils;

import android.util.Log;

import com.xxc.smartcar.wifi.bean.DeviceInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUtils {

    private static final String TAG = "HttpUtils";
    private static final int TIMEOUT = 10000; // 超时时间，单位毫秒

    // 请替换为您实际的项目ID和授权信息
    private static final String Project_Id = "0wvQdpra5k";
    private static final String Device_Name = "smartCar";

    private static final String Authorization = "version=2018-10-31&res=products%2F0wvQdpra5k%2Fdevices%2FsmartCar&et=1957941234&method=sha1&sign=VH%2Be0qvdBxEX2jJso4ih%2FCy%2B2lI%3D";

    private static final String SET_URL = "https://open.iot.10086.cn/apidebug/thingmodel/set-device-property";
    private static final String GET_URL = "https://open.iot.10086.cn/apidebug/thingmodel/query-device-property-detail";

    /**
     * 发送POST请求控制设备
     */
    public static void sendPost(DeviceInfo deviceInfo) {
        HttpURLConnection connection = null;
        DataOutputStream dataOutputStream = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(SET_URL);
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置超时时间
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            // 允许输入输出
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("authorization", Authorization);

            String jsonBody = buildDeviceControlJson(deviceInfo);
            if (jsonBody != null && !jsonBody.isEmpty()){
                dataOutputStream = new DataOutputStream(connection.getOutputStream());
                byte[] jsonBytes = jsonBody.getBytes(StandardCharsets.UTF_8);
                dataOutputStream.write(jsonBytes);
                dataOutputStream.flush();
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                Log.e(TAG, "POST请求失败，响应码：" + responseCode);
                return;
            }
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            Log.d(TAG,"POST请求响应: " + sb.toString());

        } catch (Exception e) {
            Log.e(TAG, "POST请求发生异常：" + e.getMessage(), e);
        } finally {
            // 关闭资源
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                Log.e(TAG, "关闭资源时发生异常：" + e.getMessage(), e);
            }
        }
    }


    /**
     * 发送GET请求获取设备状态
     */
    public static JSONObject sendGet() {
        HttpURLConnection connection = null;
        DataOutputStream dataOutputStream = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(GET_URL);
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");
            // 设置超时时间
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            // 允许输入输出
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", Authorization);

            // 构建请求体JSON数据
            String jsonBody = buildRequestJson();
            if (jsonBody != null && !jsonBody.isEmpty()){
                dataOutputStream = new DataOutputStream(connection.getOutputStream());
                byte[] jsonBytes = jsonBody.getBytes(StandardCharsets.UTF_8);
                dataOutputStream.write(jsonBytes);
                dataOutputStream.flush();
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                Log.e(TAG, "GET请求失败，响应码：" + responseCode);
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            Log.d(TAG,"GET请求响应: " + sb.toString());

            return new JSONObject(sb.toString());

        } catch (Exception e) {
            Log.e(TAG, "GET请求发生异常：" + e.getMessage(), e);
            return null;
        } finally {
            // 关闭资源
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                Log.e(TAG, "关闭资源时发生异常：" + e.getMessage(), e);
            }
        }
    }


    /**
     * 构建设备控制的JSON请求体
     */
    private static String buildDeviceControlJson(DeviceInfo deviceInfo) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("product_id", Project_Id);
            jsonObject.put("device_name", Device_Name);

            JSONObject params = new JSONObject();
            params.put("carDirection", deviceInfo.getCarDirection());
            params.put("led", deviceInfo.getLed());
            params.put("model", deviceInfo.getModel());
            params.put("speed", deviceInfo.getSpeed());

            jsonObject.put("params", params);
            Log.d(TAG, "发送控制数据: " + jsonObject.toString());
            return jsonObject.toString();
        } catch (JSONException e) {
            Log.e(TAG, "构建控制JSON失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 构建获取设备信息的JSON请求体
     */
    private static String buildRequestJson() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("product_id", Project_Id);
            jsonObject.put("device_name", Device_Name);
            JSONArray paramsArray = new JSONArray();
            paramsArray.put("hum");
            paramsArray.put("temp");
            jsonObject.put("params", paramsArray);
            jsonObject.put("imei", "");
            return jsonObject.toString();
        } catch (JSONException e) {
            Log.e(TAG, "构建请求JSON失败：" + e.getMessage());
            return null;
        }
    }
}